package cn.edu.dyxy.dao;

import cn.edu.dyxy.entity.User;
import cn.edu.dyxy.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author JokerQiu
 * @date 2021年12月22日 09:21
 */

public class UserDao {
    /**
     * 通过email信息获取到用户的完整信息
     *
     * @param email 邮箱
     * @return user 用户对象
     * @throws SQLException sql异常
     */
    public User getUserByEmail(String email) throws SQLException {
        User user = null;
        Connection connection = DBUtils.getConntect();
        //动态sql
        String sql = "select *  from t_user where email=?";
        //PreparedStatement：sql语言预处理
        PreparedStatement statement = connection.prepareStatement(sql);
        //把getUserByEmail中的参数email，传入到动态sql中
        statement.setString(1, email);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            user = new User();
            user.setId(resultSet.getInt("id"));
            user.setEmail(resultSet.getString("email"));
            user.setNickname(resultSet.getString("nickname"));
            user.setPassword(resultSet.getString("password"));
        }
        //关闭连接
        DBUtils.close(resultSet, statement, connection);
        return user;
    }

    /**
     * 注册用户的时候调用这个方法
     *
     * @param user 用户的信息
     * @return 执行insert语句的时候，显示的影响行数
     */
    public int saveUser(User user) throws SQLException {
        Connection connection = DBUtils.getConntect();
        String sql =
                "insert into t_user(email,nickname,password) values (?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, user.getEmail());
        ps.setString(2, user.getNickname());
        ps.setString(3, user.getPassword());
        int row = ps.executeUpdate();
        DBUtils.close(null, ps, connection);
        return row;
    }

}
